package com.gzmu.myprint.wx.util;

import com.alibaba.fastjson.JSONObject;

import java.awt.Menu;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;




public class WeixinUtil {

	public static JSONObject HttpRequest(String request , String RequestMethod , String output ){
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			//建立连接
			URL url = new URL(request);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(RequestMethod);
			if(output!=null){
				OutputStream out = connection.getOutputStream();
				out.write(output.getBytes("UTF-8"));
				out.close();
			}
			//流处理
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while((line=reader.readLine())!=null){
				buffer.append(line);
			}
			//关闭连接、释放资源
			reader.close();
			inputReader.close();
			input.close();
			connection.disconnect();
            //System.out.println("+++buffer:"+buffer.toString());
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (Exception e) {
		}
		return jsonObject;
	} 
	
//	 菜单创建（POST）   
	public static String menu_create_url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN&agentid=1";  	  
	/** 
	 * 创建菜单 
	 *  
	 * @param menu 菜单实例 
	 * @param accessToken 有效的access_token
	 * @return 0表示成功，其他值表示失败 
	 */  
	public static int createMenu(Menu menu, String accessToken) {  
	    int result = 0;  
	  
	    // 拼装创建菜单的url  
	    String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);  
	    // 将菜单对象转换成json字符串  
	    String jsonMenu = JSONObject.toJSONString(menu);
	    // 调用接口创建菜单  
	    JSONObject jsonObject = HttpRequest(url, "POST", jsonMenu);  
	  
	    if (null != jsonObject) {  
	        if (0 != jsonObject.getIntValue("errcode")) {
	            result = jsonObject.getIntValue("errcode");
	            String error = String.format("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
	            System.out.println(error); 
	        }  
	    }  
	  
	    return result;  
	}  
	public static String URLEncoder(String str){
		String result = str ;
		try {
		result = java.net.URLEncoder.encode(result,"UTF-8");	
		} catch (Exception e) {
        e.printStackTrace();
		}
		return result;
	}
	/**
	 * 根据内容类型判断文件扩展名
	 * 
	 * @param contentType 内容类型
	 * @return
	 */
	public static String getFileEndWitsh(String contentType) {
		String fileEndWitsh = "";
		if ("image/jpeg".equals(contentType))
			fileEndWitsh = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileEndWitsh = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileEndWitsh = ".amr";
		else if ("video/mp4".equals(contentType))
			fileEndWitsh = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileEndWitsh = ".mp4";
		return fileEndWitsh;
	}
	/**
	 * 数据提交与请求通用方法
	 * @param access_token 凭证
	 * @param RequestMt 请求方式
	 * @param RequestURL 请求地址
	 * @param outstr 提交json数据
	 * */
    public static int PostMessage(String access_token ,String RequestMt , String RequestURL , String outstr){
    	int result = 0;
    	RequestURL = RequestURL.replace("ACCESS_TOKEN", access_token);
    	System.out.println("RequestURL:"+RequestURL);
    	JSONObject jsonobject = WeixinUtil.HttpRequest(RequestURL, RequestMt, outstr);
    	 if (null != jsonobject) {  
 	        if (0 != jsonobject.getIntValue("errcode")) {  
 	            result = jsonobject.getIntValue("errcode");  
 	            String error = String.format("操作失败 errcode:{%s} errmsg:{%s}", jsonobject.getIntValue("errcode"), jsonobject.getString("errmsg"));  
 	            System.out.println(error); 
 	        }  
 	    }
    	return result;
    }
    
//	 获取access_token的接口地址（GET）   
    private final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CorpID&corpsecret=SECRET";  

    private static AccessToken accessToken = null;  
	/** 
	 * 获取access_token 
	 *  
	 * @param CorpID 企业Id 
	 * @param SECRET 管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret 
	 * @return 
	 */  
    private static void getAccessToken(String corpID, String secret) {	  
	    String requestUrl = access_token_url.replace("CorpID", corpID).replace("SECRET", secret);  
	    JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);  
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {
				System.out.println("获取token成功:");
	            accessToken.setTime(new Date());
	            accessToken.setToken(jsonObject.getString("access_token"));
	            accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
	            System.out.println("获取token成功:"+jsonObject.getString("access_token")+"————"+jsonObject.getIntValue("expires_in"));
	        } catch (Exception e) {  
	            accessToken = null;  
	            // 获取token失败  
	            String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));  
	            System.out.println(error);
	        }  
	    }   
	}
	
	public static String getAccessTokenString(String corpID, String secret){
		if(accessToken==null){
			System.out.println("+++fisrt Token:");
			accessToken = new AccessToken();
			getAccessToken(corpID, secret);
		}
		Date now= new Date();
		if((now.getTime()-accessToken.getTime().getTime())/1000 > (accessToken.getExpiresIn()-60)){
			System.out.println("accessToken.time:"+accessToken.getTime().getTime());
			System.out.println("now.time:"+now.getTime());
			getAccessToken(corpID, secret);
		}
		return accessToken.getToken();
	}
}  
